//
//  CPFEEDBACKController.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/4.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "CPFEEDBACKController.h"
#import "MBProgressHUD.h"
#import "TZImagePickerController.h"
#import "UIColor+YYAdd.h"
#import "JMNetHelper.h"
#import "JMHelper.h"
#import "UIDevice+YYAdd.h"
#import "NSString+Extension.h"

@interface CPFEEDBACKController ()<UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@end

@implementation CPFEEDBACKController
static NSString * const fbID = @"fbID";
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = JMColor(240, 240, 240);
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(cp_Upload:)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    [self initViews];
}
- (void)initViews
{
    CGFloat s_width = [UIScreen mainScreen].bounds.size.width;
    UILabel *qLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, s_width - 30, 30)];
    qLabel.text = @"问题和意见";
    qLabel.textColor = [UIColor colorWithHexString:@"555555"];
    qLabel.font = [UIFont systemFontOfSize:16];
    qLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:qLabel];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(-0.5, qLabel.frame.origin.y + qLabel.frame.size.height + 5, s_width+1, 165)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.borderWidth = 0.1;
    view.layer.cornerRadius = 2;
    view.layer.masksToBounds = YES;
    [self.view addSubview:view];
    
    _CP_textView = [[CPFDHeadView alloc]initWithFrame:CGRectMake(0, 0, s_width, 140)];
    _CP_textView.backgroundColor = [UIColor whiteColor];
    _CP_textView.delegate = self;
    _CP_textView.font = [UIFont systemFontOfSize:15.f];
    _CP_textView.textColor = [UIColor blackColor];
    _CP_textView.textAlignment = NSTextAlignmentLeft;
    _CP_textView.pHColor = JMColor(0x89, 0x89, 0x89);
    _CP_textView.pHolder = @"请输入不小于10个字的描述~";
    [view addSubview:_CP_textView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged:) name:UITextViewTextDidChangeNotification object:_CP_textView];
    
    _numLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, _CP_textView.frame.origin.y + _CP_textView.height, s_width - 30, 20)];
    _numLabel.font = [UIFont systemFontOfSize:14.f];
    _numLabel.textColor = [UIColor lightGrayColor];
    _numLabel.text = @"0/150";
    _numLabel.backgroundColor = [UIColor whiteColor];
    _numLabel.textAlignment = NSTextAlignmentRight;
    [view addSubview:_numLabel];
    
    
    _iLabel = [[UILabel alloc]initWithFrame:CGRectMake(qLabel.frame.origin.x, view.frame.origin.y + view.height + 10, qLabel.frame.size.width, qLabel.frame.size.height)];
    _iLabel.text = @"请提供相关问题的截图或照片(0/3)";
    _iLabel.textColor = [UIColor colorWithHexString:@"555555"];
    _iLabel.font = [UIFont systemFontOfSize:16];
    _iLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_iLabel];
    
    _CP_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _iLabel.frame.origin.y + _iLabel.frame.size.height + 10, s_width, (s_width - 50) / 4 + 20)];
    [self.view addSubview:_CP_scrollView];
    _dataSource = [NSMutableArray array];
    CPFBModel *model = [[CPFBModel alloc] init];
    model.image = [UIImage imageNamed:@"添加照片"];
    [_dataSource addObject:model];
    
    _tfView = [[UIView alloc]initWithFrame:CGRectMake(1, _CP_scrollView.frame.origin.y + _CP_scrollView.height + 10, s_width - 2, 44)];
    _tfView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tfView];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(15, 0, s_width - 30, 44)];
    _textField.placeholder = @"联系方式";
    _textField.font = [UIFont systemFontOfSize:15];
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.textColor = [UIColor colorWithHexString:@"555555"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:_textField];
    [_tfView addSubview:_textField];
    
    [self CP_PhotoPicker];
}

#pragma mark - **************** 上传反馈数据
// 循环上传，保证上传队列完成后写入数据库
- (void)cp_Upload:(id)sender
{
    JMSelf(ws);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSMutableArray *urls = [NSMutableArray array];
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queuw = dispatch_queue_create("upload_feed_back", DISPATCH_QUEUE_SERIAL);
    dispatch_group_async(group, queuw, ^{
        [ws.dataSource enumerateObjectsUsingBlock:^(CPFBModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx > 0) {
                // 1、创建 dispatch_semaphore_t对象
                dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
                NSData *imageData = [JMHelper compressImage:model.image toByte:153600];
                [JMNetHelper uploadImageData:imageData imageName:nil savePath:upload_path progress:nil status:^(BOOL success, id  _Nullable responseObject, NSString * _Nullable url) {
                    // 2、添加信号量
                    dispatch_semaphore_signal(semaphore);
                    [urls addObject:url.lastPathComponent];
                }];
                // 3、等待
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            }
        }];
    });
    [hud hideAnimated:YES];
    [_CP_textView resignFirstResponder];
    [self.view endEditing:YES];
    [self cp_show:@"上传成功！" msg:@"成功" cancel:NO handle:^(BOOL isLive) {
        [self.navigationController popoverPresentationController];
    }];
//    CPNavController *nav = (CPNavController *)self.mm_drawerController.centerViewController;
//    [nav popoverPresentationController];
}


- (void)textViewEditChanged:(NSNotification *)obj
{
    UITextView *tv = (UITextView *)obj.object;
    if (tv.text.length > 150) {tv.text = [tv.text substringToIndex:150];}
    _contentStr = tv.text;
    _numLabel.text = [NSString stringWithFormat:@"%lu/150", (unsigned long)tv.text.length];
    [self rightItemEnable];
}

- (void)textFieldEditChanged:(NSNotification *)obj
{
    UITextField *tf = (UITextField *)obj.object;
    if (tf.text.length > 11) {tf.text = [tf.text substringToIndex:11];}
    _phoneStr = tf.text;
    [self rightItemEnable];
}

- (void)rightItemEnable
{
    if (_dataSource.count > 1 || _contentStr.length > 0) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_CP_textView resignFirstResponder];
    [self.view endEditing:YES];
}

#pragma mark - **************** 初始化UICollectionView选择照片
- (void)CP_PhotoPicker
{
    UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((self.view.width - 50) / 4, (self.view.width - 50) / 4);
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    self.fdColView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 120) collectionViewLayout:layout];
    [self.fdColView registerClass:[CPFBCell class] forCellWithReuseIdentifier:fbID];
    [_CP_scrollView addSubview:self.fdColView];
    _fdColView.delegate = self;
    _fdColView.dataSource = self;
    _fdColView.backgroundColor = [UIColor whiteColor];
    _fdColView.scrollEnabled = NO;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CPFBCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:fbID forIndexPath:indexPath];
    cell.model = _dataSource[indexPath.row];
    cell.Chouse = ^(CPFBModel * _Nonnull model, BOOL isChouse) {
        isChouse?[self cp_deletePhoto:model]:[self cp_addNewImg];
    };
    return cell;
}

#pragma mark - 选择图片
- (void)cp_addNewImg
{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:3 columnNumber:3 delegate:nil pushPhotoPickerVc:YES];
    picker.allowTakePicture = NO;
    picker.allowTakeVideo = NO;
    picker.allowPickingVideo = NO;
    picker.allowPickingImage = YES;
    picker.allowPickingOriginalPhoto = NO;
    picker.allowPickingGif = NO;
    picker.allowPickingMultipleVideo = NO;
    picker.sortAscendingByModificationDate = YES;
    picker.statusBarStyle = UIStatusBarStyleLightContent;
    picker.showSelectBtn = YES;
    
    JMSelf(ws)
    [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (ws.dataSource.count < 4) {
                CPFBModel *model = [[CPFBModel alloc] init];
                model.image = obj;
                model.assets = assets[idx];
                [ws.dataSource addObject:model];
            }
        }];
        [ws rightItemEnable];
        ws.iLabel.text = [NSString stringWithFormat:@"请上传问题的照片(%ld/3)",(long)(ws.dataSource.count-1)];
        [ws.fdColView reloadData];
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - 删除照片
- (void)cp_deletePhoto:(CPFBModel *)model
{
    NSInteger index = [_dataSource indexOfObject:model];
    [_dataSource removeObjectAtIndex:index];
    [self.fdColView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    if (_dataSource.count == 1) {[self rightItemEnable];}
}
@end

#pragma mark - **************** CPFDHeadView
@implementation CPFDHeadView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setPHolder:@""];
        [self setPHColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cp_text_changed:) name:UITextViewTextDidChangeNotification object:nil];
    }
    
    return self;
}

- (void)setPHolder:(NSString *)pHolder
{
    _pHolder = pHolder;
    [self.fbhL removeFromSuperview];
    self.fbhL = nil;
    [self setNeedsDisplay];
}

- (void)cp_text_changed:(NSNotification *)notification{
    
    if (_pHolder.length == 0) {return;}
    if ([[self text] length] == 0) {
        [[self viewWithTag:999] setAlpha:1.0];
    }else{
        [[self viewWithTag:999] setAlpha:0];
    }
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    if (_pHolder.length > 0) {
        if (_fbhL == nil) {
            _fbhL = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, self.bounds.size.width - 16, 0)];
            _fbhL.lineBreakMode = NSLineBreakByWordWrapping;
            _fbhL.numberOfLines = 0;
            _fbhL.font = self.font;
            _fbhL.backgroundColor = [UIColor clearColor];
            _fbhL.textColor = self.pHColor;
            _fbhL.alpha = 0;
            _fbhL.tag = 999;
            [self addSubview:_fbhL];
        }
        _fbhL.text = self.pHolder;
        [_fbhL sizeToFit];
        [self sendSubviewToBack:_fbhL];
    }
    if ([[self text] length] == 0 && _pHolder.length >0) {
        [[self viewWithTag:999] setAlpha:1.0];
    }
}
@end

#pragma mark - **************** CPFBModel
@implementation CPFBModel
@end

#pragma mark - **************** CPFBCell
@implementation CPFBCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        UIButton *cBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [cBtn addTarget:self action:@selector(cp_delete:) forControlEvents:(UIControlEventTouchUpInside)];
        [self addSubview:cBtn];
        self.cBtn = cBtn;
        UIImageView *bIma = [[UIImageView alloc] initWithFrame:CGRectZero];
        bIma.contentMode = UIViewContentModeScaleAspectFill;
        bIma.clipsToBounds = YES;
        [self addSubview:bIma];
        self.bIma = bIma;
        UITapGestureRecognizer *sTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cp_tapImage:)];
        bIma.userInteractionEnabled = YES;
        [bIma  addGestureRecognizer:sTap];
    }
    return self;
}

- (void)setModel:(CPFBModel *)model
{
    _model = model;
    _cBtn.hidden = !model.assets;
    _bIma.image = model.image;
}

- (void)cp_delete:(UIButton *)sender
{
    if (self.Chouse) {self.Chouse(_model, YES);}
}

- (void)cp_tapImage:(UITapGestureRecognizer *)ges
{
    if (self.Chouse) {self.Chouse(_model, NO);}
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _bIma.frame = CGRectMake(0, 10, self.width-10, self.height-10);
    _cBtn.frame = CGRectMake(self.width-30, 0, 30, 30);
}
@end
